package com.elong.businesstravel.modules.home.view;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.edittextclear.EditTextClearView;
import com.android.support.jhf.network.BaseErrorListener;
import com.android.support.jhf.network.BaseStateListener;
import com.android.support.jhf.network.IErrorListener;
import com.android.support.jhf.network.IStateListener;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.AsyncHttpRequest;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.utils.InputMethodUtils;
import com.android.support.jhf.utils.ToolUtils;
import com.elong.businesstravel.ELongBusinessTravelApplication;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.BaseLinearLayout;
import com.elong.businesstravel.entitys.HotelNameSearchResult;
import com.elong.businesstravel.entitys.HotelSearchCondition;
import com.elong.businesstravel.modules.home.adapter.SimpleListAdapter;
import com.elong.businesstravel.protocol.hotel.AllInOneSearchRequest;
import com.elong.businesstravel.protocol.hotel.AllInOneSearchResponse;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;

/**
 * 输入搜索酒店的KeyWord
 * 
 * @author lenovo
 * 
 */
public class SearchKeywordView extends BaseLinearLayout implements
		OnClickListener, OnItemClickListener {

	private ELongBusinessTravelApplication mApplication;

	private List<String> mStrings = new ArrayList<String>();
	private List<HotelNameSearchResult> mHotelNameSearchResults = new ArrayList<HotelNameSearchResult>();

	private Button mSearchButton;
	private EditTextClearView mEditTextClearView;

	private OnClickListener mSearchOnClickListener;
	private OnItemClickListener mOnItemClickListener;

	private ListView mSearchListView;
	private SimpleListAdapter mSimpleListAdapter;

	private String mHotelName;

	protected HotelSearchCondition mCurrentHotelSearchCondition;

	public SearchKeywordView(Context context) {
		super(context);
		init();
	}

	public SearchKeywordView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	private void init() {
		LayoutInflater.from(mContext).inflate(R.layout.view_search_keyword,
				this, true);

		mApplication = (ELongBusinessTravelApplication) mContext
				.getApplicationContext();

		mSearchListView = (ListView) findViewById(R.id.searchListView);
		mSimpleListAdapter = new SimpleListAdapter(mContext, mStrings, "");
		mSearchListView.setAdapter(mSimpleListAdapter);

		mSearchButton = (Button) findViewById(R.id.searchButton);
		mEditTextClearView = (EditTextClearView) findViewById(R.id.keywordEditTextClearView);
		mEditTextClearView.getEditText().setImeOptions(
				EditorInfo.IME_ACTION_SEARCH);
		mEditTextClearView.getEditText().setHint("搜索");

		setListener();
	}

	private void setListener() {
		mSearchButton.setOnClickListener(this);
		mSearchListView.setOnItemClickListener(this);
		mEditTextClearView.getEditText().addTextChangedListener(
				new TextWatcher() {

					@Override
					public void onTextChanged(CharSequence s, int start,
							int before, int count) {
						String textString = s.toString();
						if (!textString.equals("") && null == mHotelName) {
							allInOneSearch(textString);
						} else {
							mStrings.clear();
							mHandler.sendEmptyMessage(0);
						}
						mHotelName = null;
					}

					@Override
					public void beforeTextChanged(CharSequence s, int start,
							int count, int after) {
					}

					@Override
					public void afterTextChanged(Editable s) {

					}
				});

		mEditTextClearView.setClearOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mStrings.clear();
				mHandler.sendEmptyMessage(0);
			}
		});

		mEditTextClearView.getEditText().setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER) {
					return true;
				}
				return false;
			}
		});
	}

	public void setCurrentHotelSearchCondition(HotelSearchCondition hotelSearchCondition){
		mCurrentHotelSearchCondition = hotelSearchCondition;
	}
	
	public void setSearchOnClickListener(OnClickListener onClickListener) {
		mSearchOnClickListener = onClickListener;
	}

	public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
		mOnItemClickListener = onItemClickListener;
	}

	public HotelNameSearchResult getHotelNameSearchResultForIndex(int position) {
		return mHotelNameSearchResults.get(position);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.searchButton: {
			if (null != mSearchOnClickListener) {
				InputMethodUtils.hideSoftKeyboard(mContext,
						mEditTextClearView.getEditText());
				v.setTag(mEditTextClearView.getEditText().getText().toString());
				mSearchOnClickListener.onClick(v);
			}
			break;
		}
		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		InputMethodUtils.hideSoftKeyboard(mContext,
				mEditTextClearView.getEditText());
		if (null != mOnItemClickListener) {
			mOnItemClickListener.onItemClick(parent, view, position, id);
		}
	}

	private Handler mHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case 0: {
				mSimpleListAdapter.notifyDataSetChanged();
				break;
			}
			default:
				break;
			}
			return false;
		}
	});

	private void allInOneSearch(String keyword) {
		DebugLog.logI("mCurrentHotelSearchCondition.product : " + mCurrentHotelSearchCondition.product);
		NetworkClient
				.getNetworkClient()
				.PostRequest(
						new AllInOneSearchRequest(
								mContext,
								mCurrentHotelSearchCondition.mSearchConditionCity.cityId,
								keyword, mCurrentHotelSearchCondition.product
										+ ""), new AllInOneSearchResponse() {
							@Override
							public void onResponse(
									ResponseHandlerInterface responseHandlerInterface) {
								mHotelNameSearchResults = ((AllInOneSearchResponse) responseHandlerInterface).hotelNameSearchResults;
								mStrings.clear();
								for (int i = 0; i < mHotelNameSearchResults
										.size(); i++) {

									String nameString = mHotelNameSearchResults
											.get(i).hotelName;
									if (TextUtils.isEmpty(nameString)) {
										nameString = mHotelNameSearchResults
												.get(i).districtsname;
									}

									if (TextUtils.isEmpty(nameString)) {
										nameString = mHotelNameSearchResults
												.get(i).bussinename;
									}

									if (TextUtils.isEmpty(nameString)) {
										nameString = mHotelNameSearchResults
												.get(i).name;
									}

									if (TextUtils.isEmpty(nameString)) {
										nameString = mHotelNameSearchResults
												.get(i).shortname;
									}

									mStrings.add(nameString);
								}
								mHandler.sendEmptyMessage(0);
							}
						}, new BaseStateListener() {
						}, new IErrorListener() {

							@Override
							public void onFailure(int statusCode,
									Header[] headers, byte[] responseBody,
									Throwable error) {
								mStrings.clear();
								mHandler.sendEmptyMessage(0);
							}
						});
	}

	public void setDefaultSearchText(String hotelName) {
		mHotelName = hotelName;
		mEditTextClearView.getEditText().setText(hotelName);
		if (!TextUtils.isEmpty(hotelName)) {
			allInOneSearch(hotelName);
		}
	}

	public void setEditTextFocus() {
		mEditTextClearView.getEditText().setFocusable(true);
		mEditTextClearView.getEditText().setFocusableInTouchMode(true);
		mEditTextClearView.getEditText().requestFocus();
		// InputMethodUtils.showSoftKeyboard(mContext,
		// mEditTextClearView.getEditText());
		InputMethodUtils.softKeyboard(mApplication);
	}

	public EditTextClearView getEditTextClearView() {
		return mEditTextClearView;
	}

}
